package cn.com.infcn.util;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;

/**
 * 
 * 描述: webservice调用帮助类
 *
 * @author xiep
 * @date 2016年9月28日 下午3:05:33
 */
public class AxisHelper {

	/**
	 * 
	 * 描述: 获取相应的字符串
	 *
	 * @param url
	 * @param namespace
	 * @param methodName
	 * @param soapActionURI
	 * @param params
	 *            例如(参数形式)params=mobileCode:13683151556,userId:x001 例如(无参数形式)params=
	 * @return
	 * @throws Exception
	 *             String
	 */
	public static String getResponseString(String url, String namespace, String methodName, String soapActionURI,
			String params) throws Exception {
 
		// 方法参数是否有值
		boolean isHasParams = false;
		String[] paramsKeyValue = null;

		if (params == null || params.trim().length() > 0) {
			isHasParams = true;
			paramsKeyValue = params.split(",");
		}

		Service service = new Service();
		Call call;
		Object obj = null;
		try {
			call = (Call) service.createCall();
			call.setTimeout(30000);
			call.setTargetEndpointAddress(url);
			call.setUseSOAPAction(true);
			call.setSOAPActionURI(soapActionURI);
			call.setOperationName(new QName(namespace, methodName));

			String[] values = null;

			if (isHasParams) {
				values = new String[paramsKeyValue.length];
				for (int i = 0; i < paramsKeyValue.length; i++) {
					String kvString = paramsKeyValue[i];
					String[] kvArray = kvString.split(":");
					String key = kvArray[0];
					String value = kvArray[1];
					int vtype = 0;
					if (kvArray.length > 2) {
						vtype = Integer.parseInt(kvArray[2]);
						QName qnameType = null;
						switch (vtype) {
						case 1:
							qnameType = XMLType.XSD_INT;
							break;
						default:
							qnameType = XMLType.XSD_STRING;
							break;
						}
						call.addParameter(new QName(namespace, key), XMLType.XSD_STRING, ParameterMode.IN);
					} else {
						call.addParameter(new QName(namespace, key), XMLType.XSD_STRING, ParameterMode.IN);
					}

					values[i] = value;
				}
			}
			call.setReturnType(XMLType.XSD_STRING);
			obj = call.invoke(values);
		} catch (Exception ex) {
			throw ex;
		}
		return (String) obj;
	}

//	public static void main(String[] args) {
//		try {
//			String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx";
//			String namespace = "http://WebXml.com.cn/";
//			String methodName = "getMobileCodeInfo";
//			String soapActionURI = "http://WebXml.com.cn/getMobileCodeInfo";
//			String params = "";
//			String responseString = AxisHelper.getResponseString(url, namespace, methodName, soapActionURI, params);
//			// System.out.println(responseString);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
}
